<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 插队（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>某银行将客户分为了若干个优先级&#xff0c; 1 级最高&#xff0c; 5 级最低&#xff0c;当你需要在银行办理业务时&#xff0c;优先级高的人随时可以插队到优先级低的人的前面。</p> 
<p>现在给出一个人员到来和银行办理业务的时间序列&#xff0c;请你在每次银行办理业务时输出客户的编号。</p> 
<p>如果同时有多位优先级相同且最高的客户&#xff0c;则按照先来后到的顺序办理。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>输入第一行是一个正整数 n ,表示输入的序列中的事件数量。(1 ≤ n ≤ 500)</p> 
<p>接下来有 n 行&#xff0c;每行第一个字符为 a 或 p 。</p> 
<p>当字符为 a 时&#xff0c;后面会有两个的正整数 num 和 x ,表示到来的客户编号为 num ,优先级为 x ;</p> 
<p>当字符为 p 时&#xff0c;表示当前优先级最高的客户去办理业务。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>输出包含若干行&#xff0c;对于每个 p &#xff0c; 输出一行&#xff0c;仅包含一个正整数 num , 表示办理业务的客户编号。</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">4<br /> a 1 3<br /> a 2 2<br /> a 3 2<br /> p</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">2</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>简单的优先队列应用。</p> 
<p>但是本题需要注意几个问题&#xff1a;</p> 
<p>1、客户编号应该不是先来后到的顺序&#xff0c;输入顺序才是</p> 
<p>2、会不会存在p数量超过a数量的情况&#xff1f;我这边考虑了这种情况&#xff0c;如果p时&#xff0c;优先队列已经没有客户了&#xff0c;那么就输出空</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<p>JS没有内置的优先队列实现&#xff0c;考试时若时间不够可以考虑使用有序数组代码。</p> 
<p>优先队列实现&#xff0c;请看&#xff1a;<a href="https://fcqian.blog.csdn.net/article/details/127695013" rel="nofollow" title="LeetCode - 1705 吃苹果的最大数目_伏城之外的博客-CSDN博客">LeetCode - 1705 吃苹果的最大数目_伏城之外的博客-CSDN博客</a></p> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; lines[0] - 0;
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 1) {
    lines.shift();
    const seq &#61; lines.map((line) &#61;&gt; line.split(&#34; &#34;));
    getResult(n, seq);
    lines.length &#61; 0;
  }
});

function getResult(n, seq) {
  const pq &#61; new PriorityQueue((a, b) &#61;&gt;
    a[0] !&#61; b[0] ? a[0] - b[0] : a[1] - b[1]
  );

  for (let i &#61; 0; i &lt; n; i&#43;&#43;) {
    const tmp &#61; seq[i];

    switch (tmp[0]) {
      case &#34;a&#34;:
        const num &#61; Number(tmp[1]);
        const x &#61; Number(tmp[2]);
        pq.offer([x, i, num]);
        break;
      case &#34;p&#34;:
        const cust &#61; pq.poll();
        if (cust) console.log(cust[2]);
        else console.log(&#34;&#34;);
    }
  }
}

// 基于堆实现优先队列
class PriorityQueue {
  constructor(cpr) {
    this.queue &#61; [];
    this.cpr &#61; cpr;
  }

  swap(a, b) {
    const tmp &#61; this.queue[a];
    this.queue[a] &#61; this.queue[b];
    this.queue[b] &#61; tmp;
  }

  // 上浮
  swim() {
    let c &#61; this.queue.length - 1;

    while (c &gt;&#61; 1) {
      const f &#61; Math.floor((c - 1) / 2);

      if (this.cpr(this.queue[c], this.queue[f]) &lt; 0) {
        this.swap(c, f);
        c &#61; f;
      } else {
        break;
      }
    }
  }

  // 入队
  offer(val) {
    this.queue.push(val);
    this.swim();
  }

  // 下沉
  sink() {
    let f &#61; 0;

    while (true) {
      let c1 &#61; 2 * f &#43; 1;
      let c2 &#61; c1 &#43; 1;

      let c;
      let val1 &#61; this.queue[c1];
      let val2 &#61; this.queue[c2];
      if (val1 &amp;&amp; val2) {
        c &#61; this.cpr(val1, val2) &lt; 0 ? c1 : c2;
      } else if (val1 &amp;&amp; !val2) {
        c &#61; c1;
      } else if (!val1 &amp;&amp; val2) {
        c &#61; c2;
      } else {
        break;
      }

      if (this.cpr(this.queue[c], this.queue[f]) &lt; 0) {
        this.swap(c, f);
        f &#61; c;
      } else {
        break;
      }
    }
  }

  // 出队
  poll() {
    this.swap(0, this.queue.length - 1);
    const res &#61; this.queue.pop();
    this.sink();
    return res;
  }

  peek() {
    return this.queue[0];
  }

  size() {
    return this.queue.length;
  }
}
</code></pre> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; Integer.parseInt(sc.nextLine());

    String[][] arr &#61; new String[n][];
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      arr[i] &#61; sc.nextLine().split(&#34; &#34;);
    }

    getResult(n, arr);
  }

  public static void getResult(int n, String[][] arr) {
    PriorityQueue&lt;int[]&gt; pq &#61;
        new PriorityQueue&lt;&gt;((a, b) -&gt; a[0] !&#61; b[0] ? a[0] - b[0] : a[1] - b[1]);

    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      String[] tmp &#61; arr[i];
      switch (tmp[0]) {
        case &#34;a&#34;:
          int num &#61; Integer.parseInt(tmp[1]);
          int x &#61; Integer.parseInt(tmp[2]);
          pq.offer(new int[] {x, i, num}); // i 是先来后到的顺序
          break;
        case &#34;p&#34;:
          int[] poll &#61; pq.poll();
          if (poll !&#61; null) System.out.println(poll[2]);
          else System.out.println(&#34;&#34;);
      }
    }
  }
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python">import queue

# 输入获取
n &#61; int(input())
seq &#61; [input().split() for _ in range(n)]


# 定义一个客户类&#xff0c;实现自定义优先级
class Customer:
    def __init__(self, num, x, index):
        &#34;&#34;&#34;
        :param num: 客户编号
        :param x: 客户优先级
        :param index: 客户先来后到顺序
        &#34;&#34;&#34;
        self.num &#61; num
        self.x &#61; x
        self.index &#61; index

    def __lt__(self, other):
        if self.x !&#61; other.x:
            return self.x &lt; other.x
        else:
            return self.index &lt; other.index


# 算法入口
def getResult(n, seq):
    pq &#61; queue.PriorityQueue()

    for i in range(n):
        tmp &#61; seq[i]

        if tmp[0] &#61;&#61; &#39;a&#39;:
            num &#61; int(tmp[1])
            x &#61; int(tmp[2])
            pq.put(Customer(num, x, i))
        elif tmp[0] &#61;&#61; &#39;p&#39;:
            if pq.qsize() &gt; 0:
                customer &#61; pq.get()
                print(customer.num)
            else:
                print(&#34;&#34;)


# 算法调用
getResult(n, seq)</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>